import {defineStore} from 'pinia'
import {loaclData, localData, sessionData} from 'xhyk-tools/vueRequest'
import {newObj, windowEvent, objNothing, stringUtil} from "xhyk-tools/xhykApi.js";
import {nextTick} from 'vue'
import XhykWeb from '../xhLayout/Edit/xhykWeb.vue'
// 多个项目共用域名时，防止本地资源混乱，添加前缀

// 默认颜色
export const theme_setting = {
  language: 'zh',
  themeType: 'light',
  menuC: '#F9F9FB',
  menuBgc: '#304156',
  // sysColor: '#3784E1',
  sysColor: '#1E90FF',
  menuLayout: 3,
  themeBgc: '#272822',
}

// region 各个发送函数

export const postMessageFn = {

  // webEvent: {
  //   wName: '',
  //   event: '',
  //   data: {},
  //   origin: "*",
  // },

  // 子项目告诉父项目，iframe加载完成事件
  loadFinish(newFullPath, oldFullPath) {
    window.$piniaTheme.webDomList.forEach(row => {
      const item = row.iframe || {}
      item.contentWindow && item.contentWindow.postMessage(newObj({
        event: 'loadFinish',
        data: {
          oldUrl: oldFullPath,
          newUrl: newFullPath,
          query: window.$route.query,
          params: window.$route.params,
          name: window.$route.name,
          path: window.$route.path,
          fullPath: window.$route.fullPath,
          meta: window.$route.meta,
          origin: window.$route.origin,
          menu: row.menu,
          wData: window.$piniaTheme.wData,
        }
      }), row.origin);
    })
  },

  // 发送广播事件
  broadcast(sendData) {
    nextTick(() => {
      window.$piniaTheme.webDomList.forEach(row => {
        const item = row.iframe || {}
        item.contentWindow && item.contentWindow.postMessage(newObj({
          event: 'broadcast',
          data: sendData
        }), '*');
      })
    })
  },

  // 初始化发送
  init(sendData) {
    nextTick(() => {
      window.$piniaTheme.webDomList.forEach(row => {
        const item = row.iframe || {}
        item.contentWindow && item.contentWindow.postMessage(newObj({
          event: 'xhykInit',
          data: sendData
        }), '*');
      })
    })
  },

  // 调用tableDialog弹窗
  tableDialog(sendData, isV2 = false) {
    if (!sendData.tableId) {
      return
    }
    // 回调给子项目
    sendData.toSave = (row) => {
      window.$piniaTheme.sendEvent({
        event: sendData.tableId,
        data: row,
        origin: sendData.origin
      })
    }
    if (isV2) {
      window.$xhykDialog.tableDialog2(sendData)
    } else {
      window.$xhykDialog.tableDialog(sendData)
    }
  },

  // 关闭弹窗
  closeDialog(sendData) {
    window.$xhykDialog.close()
  },

  // 路由相关
  router(data = {}) {
    const type = data.type || 'push'
    const url = data.url || ''
    const index = data.index || 0
    switch (type) {
      case "push":
        window.$router.push(url)
        break
      case "replace":
        window.$router.replace(url)
        break
      case "go":
        window.$router.go(index)
        break
      case 'get':
        window.$piniaTheme.sendEvent({
          event: 'getRouter',
          data: {
            path: window.$route.path,
            fullPath: window.$route.fullPath,
            route: window.$route,
            query: window.$route.query,
            params: window.$route.params,
          },
          origin: data.origin
        })
        break
    }
  },

  // 改变标签名
  changeTabName(data = {}) {
    window.$piniaTheme.changeTabNameByPath(data)
  },

  // 删除标签页
  deleteTabs(data = {}) {
    window.$piniaTheme.deleteTabs(data)
  },

  // 获取微前端共有数据
  getWData(data) {
    const wData = window.$piniaTheme.wData
    if (data.field != undefined) {
      window.$piniaTheme.sendEvent({
        event: 'wData',
        data: {
          [`${data.field}`]: wData[data.field]
        },
        origin: data.origin
      })
    } else {
      window.$piniaTheme.sendEvent({
        event: 'wData',
        data: wData,
        origin: data.origin
      })
    }
  },

  // 设置微前端共有数据
  setWData(data) {
    if (!data.field) {
      return
    }
    if (data.field != undefined) {
      window.$piniaTheme.wData[data.field] = data.value
    }
    window.$piniaTheme.sendEvent({
      event: 'setWDataCallBack',
      data: window.$piniaTheme.wData,
      origin: data.origin
    })
  },

  // 子项目互通数据
  webEvent(event) {
    if (!event.wName && !event.origin) {
      return
    }
    window.$piniaTheme.sendEvent(event)
  },

  // 路由发送改变
  changeRoute(newFullPath, oldFullPath) {
    window.$piniaTheme.webDomList.forEach(row => {
      const item = row.iframe || {}
      item.contentWindow && item.contentWindow.postMessage(newObj({
        event: 'changeRouter',
        data: {
          oldUrl: oldFullPath,
          newUrl: newFullPath,
          query: window.$route.query,
          params: window.$route.params,
          name: window.$route.name,
          path: window.$route.path,
          fullPath: window.$route.fullPath,
          meta: window.$route.meta,
          origin: window.$route.origin,
          menu: row.menu,
          wData: window.$piniaTheme.wData,
        }
      }), '*');
    })
  },

  // 添加新的iframe。处理编辑页
  addWebDom(data) {
    if (!data.wPath) {
      return
    } else {
      const tempList = data.wPath.split('/')
      let origin = ''
      tempList.find(tempStr => {
        if (tempStr.includes('http')) {
          origin = `${tempStr}//`
        } else if (tempStr) {
          origin = `${origin}${tempStr}`
          return true
        }
      })
      data.origin = origin
    }
    const tempObj = {
      // 主键ID，最大长度60字符
      id: data.id,
      // 路由名称，最大长度255字符
      name: data.id,
      // 标题，最大长度255字符
      title: data.title,
      // 菜单类型，0：菜单，1：编辑页，2：API
      menuType: 1,
      // 图标
      icon: data.icon,
      // 组件路径
      path: data.path,
      // 微前端路径
      wPath: 'http://192.168.0.48:633/#/test',
      jumpUrl: data.jumpUrl,
      origin: data.origin,
      component: XhykWeb
    }
    window.$piniaTheme.wWebMenu.push(tempObj)
    window.$piniaTheme.menuButtonList.push(tempObj)
    window.$router.addRoute(window.$xhykOptions.parentRouteName || 'mainIndex', tempObj)
    window.$piniaTheme.sendEvent({
      event: data.id,
      data: tempObj,
      origin: data.origin
    })
  },

  // 删除iframe。只处理编辑页
  delWebDom(data) {
    if (!data.path) {
      return
    }
    const thisMenu = window.$piniaTheme.wWebMenu.find(row => row.path == data.path)
    if (thisMenu) {
      window.$piniaTheme.wWebMenu = window.$piniaTheme.wWebMenu.filter(row => row.id != thisMenu.id)
      window.$piniaTheme.menuButtonList = window.$piniaTheme.menuButtonList.filter(row => row.id != thisMenu.id)
      window.$router.removeRoute(thisMenu.id)
      window.$piniaTheme.deleteTabs(thisMenu.path)
      window.$piniaTheme.sendEvent({
        event: data.id,
        data: thisMenu,
        origin: data.origin
      })
    }
  }
}

// endregion

export const themeData = defineStore('themeData', {
  // 定义属性
  state: () => {
    return {
      name: 'themeData',

      // region 菜单与权限

      // 设置菜单时的列表参数，undefined时则根据目录进行获取
      // menuListParams: -1,

      // 全部菜单列表（包含菜单页，编辑页，api，微前端）
      menuList: [],

      // 树形结构的菜单列表（只有菜单页）
      menuTree: [],

      // 已经加载过菜单
      haveGetMenu: false,

      // 每个菜单的层级列。如：[ [{父级1},{子级1}], [{父级1},{子级2}], ]
      menuLevel: [],

      // 编辑菜单
      menuButtonList: [],

      // 当前活跃的一级菜单
      nowMenuFather: sessionData.get(`${window.$xhykOptions.themePrefix}_nowMenuFather`) || {},

      // 当前活跃的子级菜单
      nowMenuChild: sessionData.get(`${window.$xhykOptions.themePrefix}_nowMenuChild`) || {},

      // 是否打开菜单显示
      openMenu: {
        close: false,
        resetTab: false
      },

      // 菜单导航栏布局。
      // 1：经典：普通菜单。
      // 2：导航式：左边标签导航菜单。
      // 3：导航式弹窗列表：左边标签导航菜单。
      menuLayout: loaclData.get(`${window.$xhykOptions.themePrefix}_menuLayout`) || theme_setting.menuLayout,

      // endregion

      // region 微前端

      // 微前端菜单
      wWebMenu: [],

      // 微前端dom对象
      webDomList: [
        // {menu: {},iframe: {},name: ''}
      ],

      // 当前激活的微前端名称
      nowWebName: '',

      // 当前刷新的微前端名称
      nowWebRefresh: '',


      // 微前端共有数据
      wData: {
        name: 'xhyk',
        wWebMenu: [],
      },

      // endregion

      // region 路由插槽
      isSlotRoute: false,
      // endregion

      // region 导航标签页
      // 标签页列表
      tabsList: sessionData.get(`${window.$xhykOptions.themePrefix}_tabsList`) || [],

      // 当前关闭/刷新的编辑标签页
      editTabs: [
        // editId: 编辑的id,name:路由名称,event：操作事件
        // {editId: '', name: '', event: 'close/refresh'}
      ],

      // endregion


      // region 导航用户信息
      dropdown: {
        title: '',
        icon: 'SwitchButton',
        width: '104px',
      },
      dropdownItem: undefined,
      // endregion

      // region 刷新页面
      excludeList: ["jumpRoute"],
      // endregion

      // 语言
      language: loaclData.get(`${window.$xhykOptions.themePrefix}_language`) || theme_setting.language,

      // region 颜色，主题
      // 黑暗/亮色主题
      themeType: loaclData.get(`${window.$xhykOptions.themePrefix}_themeType`) || theme_setting.themeType,

      // 菜单活跃字体颜色
      menuC: loaclData.get(`${window.$xhykOptions.themePrefix}_menuC`) || theme_setting.menuC,

      // 菜单背景色
      menuBgc: loaclData.get(`${window.$xhykOptions.themePrefix}_menuBgc`) || theme_setting.menuBgc,

      // 系统配色
      sysColor: loaclData.get(`${window.$xhykOptions.themePrefix}_sysColor`) || theme_setting.sysColor,

      // 系统背景色
      themeBgc: loaclData.get(`${window.$xhykOptions.themePrefix}_themeBgc`) || theme_setting.themeBgc,
      // endregion

      // 右击菜单
      rightMenu: false,

    }
  },
  // 定义方法
  actions: {
    saveToLocal(data = {}) {
      for (let key in data) {
        this[key] = data[key]
        localData.set(`${window.$xhykOptions.themePrefix}_${key}`, data[key])
      }
      if (data.menuLayout) {
        windowEvent.resize()
      }
    },

    saveToSession(data = {}) {
      for (let key in data) {
        this[key] = data[key]
        sessionData.set(`${window.$xhykOptions.themePrefix}_${key}`, data[key])
      }
    },

    // region 微前端

    // 根据origin获取iframe对象
    getIframeByOrigin(origin) {
      return window.$piniaTheme.webDomList.find(row => row.origin == origin)
    },

    // 根据name获取iframe对象
    getIframeByName(wName) {
      return window.$piniaTheme.webDomList.find(row => row.name == wName)
    },

    // 发送事件(单子项目)
    // webEvent: {
    //   wName: '',
    //   event: '',
    //   data: {},
    //   origin: "*",
    // },
    sendEvent(webEvent = {}, otherData = {}) {
      nextTick(() => {
        if (!webEvent.event) {
          return
        }
        if (webEvent.event == 'broadcast') {
          postMessageFn.broadcast(webEvent.data, otherData)
        } else if (webEvent.event == 'xhykInit') {
          postMessageFn.init(webEvent.data, otherData)
        } else if (webEvent.wName) {
          const thisIframe = window.$piniaTheme.getIframeByName(webEvent.wName)
          if (thisIframe) {
            thisIframe.iframe.contentWindow &&
            thisIframe.iframe.contentWindow.postMessage(newObj(webEvent), thisIframe.origin);
          }
        } else if (webEvent.origin) {
          const thisIframe = window.$piniaTheme.getIframeByOrigin(webEvent.origin)
          if (thisIframe) {
            thisIframe.iframe.contentWindow &&
            thisIframe.iframe.contentWindow.postMessage(newObj(webEvent), thisIframe.origin);
          }
        }
      })
    },

    // endregion


    // region 导航标签

    // 根据path改变标签名
    changeTabNameByPath(data) {
      const path = data.path || ''
      const newName = data.newName || ''
      const otherData = data.otherData || {}
      if (!path) {
        return
      }
      const thisTab = window.$piniaTheme.tabsList.find(row => {
        const tempPath = stringUtil.getStrLeft(row.path, '?', row.path)
        if (tempPath == path) {
          if (objNothing(otherData || {})) {
            return true
          } else {
            let isThis = true
            // 同时需要满足其他参数
            for (let key in otherData) {
              const params = `${key}=${otherData[key]}`
              if (!row.fullPath.includes(params)) {
                isThis = false
                break
              }
            }
            if (isThis) {
              return true
            }
          }
        }
      })
      if (thisTab) {
        thisTab.title = newName
        window.$piniaTheme.saveToSession({
          tabsList: window.$piniaTheme.tabsList
        })
      }
    },

    // 删除标签页
    deleteTabs(data) {
      const path = data.path || ''
      const otherData = data.otherData || {}
      if (!path) {
        return
      }
      const tabsList = window.$piniaTheme.tabsList.filter(row => {
        const tempPath = stringUtil.getStrLeft(row.path, '?', row.path)
        if (tempPath == path) {
          if (objNothing(otherData || {})) {
            return false
          } else {
            let isThis = true
            // 同时需要满足其他参数
            for (let key in otherData) {
              const params = `${key}=${otherData[key]}`
              if (!row.fullPath.includes(params)) {
                isThis = false
                break
              }
            }
            if (isThis) {
              return false
            }
          }
        }
        return true
      })
      window.$piniaTheme.tabsList = tabsList
      window.$piniaTheme.saveToSession({
        tabsList: tabsList
      })
    },

    // endregion
    
    // region 获取表格字段的排序方式
    getTableField(fieldList, name) {
      const temp = localData.get(name) || []
      if (temp.length <= 0){
        return fieldList
      }

      fieldList?.forEach((item) => {
        const thisField = temp.find(row => row.prop == item.prop && row.prop)
        if (thisField) {
          item.show = thisField.show
          item.align = thisField.align
          item.width = thisField.width
          item.sortable = thisField.sortable
          item.fixed = thisField.fixed
          return
        }
        const thisLabel = temp.find(row => row.label == item.label && row.label)
        if (thisLabel) {
          item.show = thisLabel.show
          item.align = thisLabel.align
          item.width = thisLabel.width
          item.sortable = thisLabel.sortable
          item.fixed = thisLabel.fixed
          return;
        }

        const thisSlot = temp.find(row => row.slot == item.slot && row.slot)
        if (thisSlot) {
          item.show = thisSlot.show
          item.align = thisSlot.align
          item.width = thisSlot.width
          item.sortable = thisSlot.sortable
          item.fixed = thisSlot.fixed
          return;
        }

        const thisType = temp.find(row => row.type == item.type && row.type)
        if (thisType) {
          item.show = thisType.show
          item.align = thisType.align
          item.width = thisType.width
          item.sortable = thisType.sortable
          item.fixed = thisType.fixed
          return;
        }
      })
      return fieldList || [];
    },
    // endregion

  },
})